import { appRef } from "@/models/app.ref";
import { BaseServices } from "./base.services";
import { Method, Uri, RespInfo, config } from "./config";
import { RoleEnum } from "@/models/@types";

export class FileService extends BaseServices {
  private static _ins: FileService = new FileService();
  public static get ins(): FileService {
    return this._ins ? this._ins : (this._ins = new FileService());
  }

  /** 上传文件 */
  public uploadFile(file: File): Promise<string> {
    const url = "https://www.cwjiaoyu.cn/fileApi/share/upload_file/";
    const data = new FormData();
    data.append("file", file);
    return new Promise<string>((reslove) => {
      this.request(url, data).then(async (res: RespInfo<string>) => {
        reslove(res.info);
      });
    });
  }
  /** 发送消息 */
  public send(filename: string, question: string): Promise<string> {
    const questionUid = appRef.chatFile.addMenuAnswer(RoleEnum.User, question);
    const url = " https://www.cwjiaoyu.cn/fileApi/share/message/";
    const data = { filename, question };
    return new Promise<string>((reslove, reject) => {
      this.request(url, data)
        .then(async (res: { answer: string }) => {
          appRef.chatFile.addMenuAnswer(RoleEnum.AI, res.answer, questionUid);
          reslove(res.answer);
        })
        .catch((err) => {
          appRef.chatFile.addMenuAnswer(RoleEnum.AI, `Error sending message. Please try again. <br> ${err.stack}`, questionUid);
          reject(err.stack);
        });
    });
  }
  /** 重新发送消息 */
  public refreshSend(filename: string, quote: string): Promise<string> {
    const currSession = appRef.chatFile?.currMenu?.sessions?.find((val) => val.quote === quote);
    const session = appRef.chatFile?.currMenu?.sessions?.find((val) => val.uid === quote);
    const url = "https://www.cwjiaoyu.cn/fileApi/share/message/";
    const data = { filename, question: session.richtext };
    return new Promise<string>((reslove) => {
      this.request(url, data)
        .then(async (res: { answer: string }) => {
          appRef.chatFile.removeMenuAnswer(currSession.uid, false);
          appRef.chatFile.addMenuAnswer(RoleEnum.AI, res.answer, quote);
          reslove(res.answer);
        })
        .catch((err) => {
          appRef.chatFile.removeMenuAnswer(session.uid, false);
          appRef.chatFile.addMenuAnswer(RoleEnum.AI, `Error sending message. Please try again. <br> ${err.stack}`, quote);
          reslove(err.stack);
        });
    });
  }
}

export const fileService: FileService = FileService.ins;
